package com.data.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * Create with Intellij IDEA.
 * Description：
 * User:Zero
 * Date:2021/5/12
 * Time:16:41
 */
public class TreeLinkedList {
    public static Node addChildren(Node node,ArrayList<Node> nodeList){
        node.setChildren(new ArrayList<Node>());
       // System.out.println("nodeList.size():"+nodeList.size());
        //System.out.println("data:"+node.getData());
        //System.out.println("层级："+node.getLevel());
        for (Node it:nodeList){
            if (node.getId()==it.getPid()){
                it.setLevel(node.getLevel()+1); //设置层级

                if (node.getChildren()==null){  //初始化上一级节点的子节点
                    node.setChildren(new ArrayList<Node>());
                }

                node.getChildren().add(addChildren(it,nodeList));
            }
        }
//        System.out.println("addChildren");
        return node;  //直到没有子节点
    }
    public static void main(String[] args) {
        Node node1 = new Node("a", 1,0);
        Node node2 = new Node("b", 2,1);
        Node node3 = new Node("c", 3,2);
        Node node4 = new Node("d", 4,1);
        Node node5 = new Node("e", 5,2);
        Node node6 = new Node("f", 6,1);
        Node node7 = new Node("g", 7,4);
        Node node8 = new Node("h", 8,6);
        ArrayList<Node> list = new ArrayList<>();

        list.add(node1); list.add(node2); list.add(node3); list.add(node4);
        list.add(node5); list.add(node6); list.add(node7); list.add(node8);


        /**
         * 把八个对象存储到按照树进行存储
         */
        ArrayList<Node> finalNode = new ArrayList<>();
        for (Node node:list){
            if (node.getPid()==0){
                node.setLevel(1);
                finalNode.add(addChildren(node,list));

            }
        }

        System.out.println("第一层");
        System.out.println(finalNode.get(0).getData());

        System.out.println("第二层");
        for (int i = 0; i < finalNode.get(0).getChildren().size(); i++) {
            System.out.println(finalNode.get(0).getChildren().get(i).getData());
        }

        System.out.println("第三层");
        for (int i = 0; i < finalNode.get(0).getChildren().size(); i++) {
            List<Node> children = finalNode.get(0).getChildren().get(i).getChildren();
            for (int j = 0; j <children.size() ; j++) {
                System.out.println(children.get(i).getData());
            }
        }

    }

}
